package br.slic.eao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.slic.exception.EAOException;

@Stateless
public class GenericEAO<T> implements EAO<T> {

	public static final String UNIT_NAME = "SlicPU";
	protected EntityManager entityManager;	
	
	@SuppressWarnings("rawtypes")
	private Class myClass;
	
	@SuppressWarnings("rawtypes")
	public GenericEAO(Class myClass, EntityManager em) {
		this.entityManager = em;
		this.myClass = myClass;
	}	

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@Override
	public void persist(T object) throws EAOException {
		try {
			entityManager.persist(object);
		} catch (Exception e) {
			throw new EAOException(e);
		}
	}

	@Override
	public T saveOrUpdate(T object) throws EAOException {
		T result = null;
		try {
			result = (T) entityManager.merge(object);
		} catch (Exception e) {
			throw new EAOException(e);
		}
		return result;
	}

	@Override
	public void remove(T object) throws EAOException {
		try {
			object = entityManager.merge(object);
			entityManager.remove(object);
		} catch (Exception e) {
			throw new EAOException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public T selectById(long id) throws EAOException {
		T result = null;
		try {
			result = (T) entityManager.find(myClass , id);
		} catch (Exception e) {
			throw new EAOException(e);
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll() throws EAOException {
		List<T> result = new ArrayList<T>();
		try {
			Query query = entityManager.createQuery("from "+myClass.getName());
			result = query.getResultList();
		} catch (Exception e) {
			throw new EAOException(e);
		}
		return result;
	}
	
    @SuppressWarnings("unchecked")
    public List<T> loadLazyRelationship(Object myEntity, String relacionamento) throws EAOException {
    	List<T> objetos = new ArrayList<T>();
    	try {
    		StringBuilder sql = new StringBuilder();
    		sql.append("select o from ");
    		sql.append(this.myClass.getSimpleName());
    		sql.append(" o LEFT JOIN FETCH o.");
    		sql.append(relacionamento);
    		sql.append(" r where r = :myEntity");
    		
    		String sqlStr = sql.toString();
    		Query query = entityManager.createQuery(sqlStr);
    		query.setParameter("myEntity", myEntity);
    		objetos = query.getResultList();
    	} catch (Exception e) {
    		throw new EAOException(e);
    	}        
    	return objetos;
  }	

}